package cn.com.yx.ms.controller;

import cn.com.yx.ms.application.web.ApiQuery;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.TestModel;
import cn.com.yx.ms.domain.mq.MessageBase;
import cn.com.yx.ms.domain.mq.upstream.U_Message4009;
import cn.com.yx.ms.domain.template.ImageModel;
import cn.com.yx.ms.domain.template.RegionModel;
import cn.com.yx.ms.domain.template.ResourceModel;
import cn.com.yx.ms.domain.template.VideoModel;
import cn.com.yx.ms.service.ICommonService;
import cn.com.yx.ms.service.IRepairService;
import cn.com.yx.ms.service.ISysService;
import cn.com.yx.ms.service.ITestService;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.security.Des3Kit;
import cn.yx.framework.security.MD5Util;
import cn.yx.framework.security.RSAKit;
import cn.yx.framework.system.SystemUtil;
import cn.yx.framework.util.DateUtil;
import cn.yx.framework.view.ApiResult;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

// import org.java_websocket.drafts.Draft_17;

/**
 * 应用中心
 */
@RestController
@RequestMapping(value = "test")
@Api(value = "测试接口", description = "用于测试CRUD的接口")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Resource
    private MessageSource messageSource;
    @Resource
    private ISysService iSysService;
    @Resource
    private ICommonService iCommonService;


    //    @Resource
//    private MyWebSocket myWebSocket;
    @Resource
    private ITestService iTestService;
    @Resource
    private IRepairService iRepairService;
    @Resource
    private RedisTemplate redisTemplate;
    //    @Resource
    private Jedis jedis;


    @PostMapping()
    @ApiOperation(value = "创建测试实体", notes = "创建测试实体")
    @ApiImplicitParam(paramType = "body", name = "testmode", dataType = "Map", required = true, value = "测试实体详细信息")
    public ApiResult create(@RequestBody @Validated TestModel testModel, BindingResult bindingResult) {
        String uuid = UUID.randomUUID().toString();
        String capText = DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        testModel.setId(uuid);
        redisTemplate.opsForValue().set(uuid, testModel, 600 * 5, TimeUnit.SECONDS);
        System.out.println(uuid);

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "", iTestService.insert(testModel));
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除测试实体", notes = "删除测试实体")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "实体ID")
    public ApiResult delete(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iTestService.delete(id));
    }

    @PutMapping()
    @ApiOperation(value = "更新测试实体", notes = "更新测试实体")
    @ApiImplicitParam(paramType = "body", name = "testmode", dataType = "Map", required = true, value = "测试实体详细信息")
    public ApiResult updateModel(@RequestBody @Validated TestModel testModel, BindingResult bindingResult) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "更新成功", iTestService.update(testModel));
    }

    @PatchMapping()
    @ApiOperation(value = "部分更新测试实体", notes = "部分更新测试实体")
    @ApiImplicitParam(paramType = "body", name = "testmode", dataType = "Map", required = true, value = "测试实体详细信息")
    public ApiResult updateProperty(@RequestBody @Validated TestModel testModel, BindingResult bindingResult) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "更新成功", iTestService.update(testModel));
    }


    @ResponseBody
    @RequestMapping(value = "page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的寻人寻亲数据")
    public ApiResult find(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        System.out.println(BaseConstant.getAesConfig().getSecretKey());

        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("title", request.getParameter("title"));
        query.getConditions().put("count", request.getParameter("count"));
        query.getConditions().put("starttime", request.getParameter("starttime"));
        query.getConditions().put("endtime", request.getParameter("endtime"));

        return new ApiResult<>(AppConstant.MSG_SUCCESS, iTestService.find(query));
    }

    @ResponseBody
    @RequestMapping(value = "{id}", method = GET)
    @ApiImplicitParam(paramType = "query", name = "id", dataType = "String", required = true, value = "测试ID")
    @ApiOperation("测试接口")
    public ApiResult findById(@PathVariable("id") String id, HttpServletRequest request) throws Exception {

        // 字符串超过一定的长度
        String str = "ABCdef123中文~!@#$%^&*()_+{};/1111111111111111111111111AAAAAAAAAAAJDLFJDLFJDLFJLDFFFFJEIIIIIIIIIIFJJJJJJJJJJJJALLLLLLLLLLLLLLLLLLLLLL" +
                "LLppppppppppppppppppppppppppppppppppppppppp===========================------------------------------iiiiiiiiiiiiiiiiiiiiiii";
        System.out.println("\n原始的字符串为------->" + str);
        float len0 = str.length();
        System.out.println("原始的字符串长度为------->" + len0);

        String ys = Des3Kit.compress(str);
        System.out.println("\n压缩后的字符串为----->" + ys);
        float len1 = ys.length();
        System.out.println("压缩后的字符串长度为----->" + len1);


        //获取操作系统硬件信息
        String[] ipMac = SystemUtil.getIpMac();
        String cpuId = SystemUtil.getCpuId();
        System.out.println(ipMac[0]);
        System.out.println(ipMac[1]);
        System.out.println(cpuId);


        //加密信息测试
        Map<String, byte[]> keyMap = RSAKit.generateKeyBytes();
        //公钥
        PublicKey publicKey = RSAKit.restorePublicKey(keyMap.get(RSAKit.PUBLIC_KEY));
        String pubKey = RSAKit.getKeyString(publicKey);
        //String compressPubKey = Des3Kit.compress(pubKey);
        //私钥
        PrivateKey privateKey = RSAKit.restorePrivateKey(keyMap.get(RSAKit.PRIVATE_KEY));
        String prikey = RSAKit.getKeyString(privateKey);
        PrivateKey privateKey1 = RSAKit.getPrivateKey(prikey);
        //String compressprikey = Des3Kit.compress(pubKey);


        //加密源
        String compname = "苏州桠鑫电子科技有限公司"; //企业名称
        String compcode = "123456789012345678"; //统一信用代码
        String contactmobile = "18952403334"; //联系电话
        String contactemail = "31601585@qq.com"; //联系人邮箱
        String appid = UUID.randomUUID().toString().replace("-", ""); //应用ID
        String appsecret = prikey; //密钥
        String cpuid = cpuId; //cpuid
        String mac = ipMac[1]; //mac
        int applydevnumber = 2000; //申请设备数量

        String source = compname + "|"
                + compcode + "|"
                + contactmobile + "|"
                + contactemail + "|"
                + appid + "|"
                + appsecret + "|"
                + cpuid + "|"
                + mac + "|"
                + applydevnumber;

        //公钥加密
        byte[] encodedText = RSAKit.RSAEncode(publicKey, source.getBytes());
        System.out.println("RSA encoded: " + Base64.encodeBase64String(encodedText));


        for (int i = 1; i <= applydevnumber; i++) {
            //license content
            byte[] content = RSAKit.RSAEncode(publicKey, (source + String.format("%04d", i)).getBytes());
            //license no
            String md5 = MD5Util.md5Str(Base64.encodeBase64String(content));
            System.out.println("第" + i + "号，license no:" + md5 + ",license content:" + Base64.encodeBase64String(content));
        }

        //私钥解密
        System.out.println("RSA decoded: " + RSAKit.RSADecode(privateKey, encodedText));


//        jedis = new Jedis("192.168.0.249", 6379);
//        String k1 = "spring:session:sessions:05a9ffb6-f42d-4680-b7b5-fe3e3b4de06d";
//        String k2 = "maxInactiveInterval";
//
//        //jedis.hgetAll();
//        jedis.hget(k1, k2);
//        Object object = request.getSession().getAttribute("userprofile");
//
//        Set<String> keySet = redisTemplate.opsForHash().keys("spring:session:sessions:970f1e51-4e4d-479f-8c7e-9d89a567e2c6");
//        List<Object> values = redisTemplate.opsForHash().multiGet("spring:session:sessions:970f1e51-4e4d-479f-8c7e-9d89a567e2c6", keySet);
//        int i = 0;
//        for (String k : keySet) {
//            // k is the key
//            // and here is the value corresponding to the key k
//            Object value = values.get(i++);
//        }
//
//        Object obj = redisTemplate.opsForValue().get(id);

        return new ApiResult<>(AppConstant.MSG_SUCCESS, iTestService.findOne(id));
    }

    @ResponseBody
    @RequestMapping(value = "resource", method = GET)
    public ApiResult findTest(HttpServletRequest request) throws Exception {

        // region 媒体资源
        List<RegionModel> regions = new ArrayList<>();
        List<ResourceModel> resources = new ArrayList<>();

        // region 视频资源
        VideoModel videoModel = new VideoModel();
        videoModel.setVideotype(0);
        videoModel.setLocalpath("resource/video/1.mp4");

        ResourceModel<VideoModel> resourceModel = new ResourceModel<>();
        resourceModel.setName("视频1.mp4");
        resourceModel.setType("video");
        resourceModel.setOrderindex(0);
        resourceModel.setData(videoModel);
        resources.add(resourceModel);
        // endregion

        // region 图片资源

        ImageModel imageModel = new ImageModel();
        imageModel.setUrl("2014/oaaaa.jpg");
        imageModel.setLocalpath("resource/image/1.jpg");

        ResourceModel<ImageModel> resourceImage = new ResourceModel<>();
        resourceImage.setName("图片1.jpg");
        resourceImage.setType("image");
        resourceImage.setOrderindex(1);
        resourceImage.setData(imageModel);
        resources.add(resourceImage);

        // endregion

        // endregion

        // region 公告资源

        List<RegionModel> regionNoticess = new ArrayList<>();
        List<ResourceModel> resourceNotices = new ArrayList<>();


        // region 公告赋值


        // endregion

        // endregion


        RegionModel region = new RegionModel();
        region.setRegioncode("REGION_VIDEO_A");
        region.setCount(1);
        region.setResources(resources);
        regions.add(region);

        String json = com.alibaba.fastjson.JSON.toJSONString(regions);
        System.out.println(json);


        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, null, regions);
    }


    @ResponseBody
    @RequestMapping(value = "5001", method = RequestMethod.GET)
    @ApiOperation("5001测试")
    public ApiResult find5001(HttpServletRequest request) throws Exception {

        MessageBase<U_Message4009> m4009 = new MessageBase<>();
        m4009.setMsgid(UUID.randomUUID().toString());
        m4009.setDeviceid("192.168.101.34");
        m4009.setCommand(4009);
        m4009.setType("request");
        this.post("http://localhost:8081/websocket/192.168.101.34/4009/", com.alibaba.fastjson.JSON.toJSONString(m4009));

        String result = sendGet(BaseConstant.getBusApiConfig().getUrl() + "?deviceid=192.168.0.200&command=5001&type=request", "");
        return new ApiResult<>(AppConstant.MSG_SUCCESS, result);
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
        com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }


    @ResponseBody
    @RequestMapping(value = "wsclient", method = RequestMethod.GET)
    @ApiOperation("websocket测试")
    public ApiResult wsClient(HttpServletRequest request) throws Exception {

//        String wsUrl = "ws://localhost:8081/websocket/192.168.0.200";
//        WebSocketClientUtil c = new WebSocketClientUtil(new URI(wsUrl), new Draft_17()); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts
//        c.connect();

        return new ApiResult().success();
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    @RequestMapping("qrcode")
    public ApiResult generateQRCode() {
        iCommonService.generateQRCode(BaseConstant.getUploadConfig().getFilepath(), "test", "hello qrcode");
        return new ApiResult().success();
    }

    @RequestMapping("reportTest")
    public ApiResult reportTest() throws Exception {
        iRepairService.alertReport("192.168.100.1", "01", "温度过高");
        return new ApiResult().success();
    }
}